#!/usr/bin/env python3
import sys
import time
import backtrader as bt
import datetime as dt
import baostock as bs
import tushare as ts
import datetime
import matplotlib.pyplot as plt
#from ccxtbt import CCXTStore
from config import BINANCE, ENV, PRODUCTION, COIN_TARGET, COIN_REFER, DEBUG

from dataset.dataset import CustomDataset
from nowStrategies.nowBehindKeyPointsStrategy import nowBehindKeyPointsStrategy
from nowStrategies.nowKeyPointsStrategy import nowKeyPointsStrategy
from nowStrategies.nowTimeBehindtrategy import nowTimeBehindtrategy
from sizer.percent import FullMoney
from strategies.AlphaPortfolioStrategy import AlphaPortfolioStrategy
from strategies.AverageStrategy import AverageStrategy
from strategies.BollingerBand import BollingerBand
from strategies.KeyPointsStrategy import KeyPointsStrategy
from strategies.MyStrategy import MyStrategy
from strategies.RSIMACDMultiTF import RSIMACDMultiTF
from strategies.SM25Bias import SM25Bias
from strategies.Ssa import Ssa
from strategies.SsaStrategy import SsaStrategy
from strategies.TailPlateStrategy import TailPlateStrategy
from strategies.TestStrategy import TestStrategy
from strategies.base import StrategyBase
from strategies.basic_rsi import BasicRSI
from strategies.boll import Boll
from util.GetBaostockDat import GetBaostockDat
from util.GetTushareDat import GetTushareDat
from utils import print_trade_analysis, print_sqn, send_telegram_message

# 统计回测周期内K线数量
def bar_size(df, fromdate, todate):
    #df = pd.read_csv(datapath)
    return len(df[(df['date'] >= fromdate.strftime('%Y-%m-%d'))
            & (df['date'] <= todate.strftime('%Y-%m-%d'))])
def main():
    MIN_PERIOD = 30
    lg = bs.login(user_id='anonymous', password='123456')
    pro = ts.pro_api(token='936d1029be68a59a3e77eeb9e4eb1ea3c36502bd4b4bf9e1aae91bd8')
    stk_pools = ['sh.600000', 'sh.600850','sh.600857','sh.600862','sh.600865','sh.600866','sh.600973','sh.600986','sh.600988','sh.600992','sh.600995','sh.600996','sh.600087','sh.600077']
    #stk_pools = ['sh.600986']
    stk_pools = ['sh.600000']
    cerebro = bt.Cerebro(quicknotify=True)
    fromdate = datetime.datetime(2000,11,6)
    todate = datetime.datetime(2022, 12, 5)
    for stk_code in stk_pools:
        date = '2000-11-6'
        data =GetBaostockDat().getData(bs,stk_code,date,'d',fromdate,todate,False)
        if data is None:
            continue
        #data = GetTushareDat().getData(pro,stk_code, date, 'd', fromdate, todate)
        cerebro.adddata(data,name=stk_code)

        #cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes, compression=30)

    broker = cerebro.getbroker()
    broker.setcommission(commission=0.001, name=COIN_TARGET)  # 佣金
    broker.setcash(10000.0)  #
    #cerebro.addsizer(bt.sizers.FixedSize, stake=100) # 设定需要设定每次交易买入的股数

    cerebro.addsizer ( FullMoney )
    # Analyzers to evaluate trades and strategies
    # SQN = Average( profit / risk ) / StdDev( profit / risk ) x SquareRoot( number of trades )
    cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
    cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")
    # Include Strategy
    cerebro.addstrategy ( nowTimeBehindtrategy )
    # Starting backtrader bot
    initial_value = cerebro.broker.getvalue()
    print('Starting Portfolio Value: %.2f' % initial_value)
    result = cerebro.run()
    # Print analyzers - results
    final_value = cerebro.broker.getvalue()
    print('Final Portfolio Value: %.2f' % final_value)
    print('Profit %.3f%%' % ((final_value - initial_value) / initial_value * 100))
    try :
       # 性能输出：
       print('夏普率:', result.analyzers.mysharpe.get_analysis())
       print_trade_analysis(result[0].analyzers.ta.get_analysis())
       print_sqn(result[0].analyzers.sqn.get_analysis())
    except Exception as e:
        1 + 1
    finally:
        #plt.savefig("D:\\figure.jpg")
        fig =cerebro.plot(volume=False)
        #plt.close("all")
        #show = fig[0][0]
        #show.savefig("D:\\figure.jpg", width=16, height=9, dpi=300)
if __name__ == "__main__":
    try:
        main()
        #sys.exit(0)
    except KeyboardInterrupt:
        print("finished.")
        time = dt.datetime.now().strftime("%d-%m-%y %H:%M")
        send_telegram_message("Bot finished by user at %s" % time)
    except Exception as err:
        send_telegram_message("Bot finished with error: %s" % err)
        print("Finished with error: ", err)
        raise